package com.kujie.loader.vector;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
@Slf4j
public class PdfFileLoader implements ResourceLoader {
    @Override
    public String getContent(InputStream inputStream) {
        try (PDDocument document = PDDocument.load(inputStream)) {
            if (document.isEncrypted()) {
                log.warn("PDF文件已加密，尝试解密...");
                try {
                    document.setAllSecurityToBeRemoved(true);
                } catch (Exception e) {
                    log.warn("无法移除PDF安全设置");
                }
            }

            if (document.getNumberOfPages() == 0) {
                log.warn("PDF文件没有页面");
                return "";
            }

            PDFTextStripper textStripper = new PDFTextStripper();

            // 限制页数以避免内存问题
            int totalPages = document.getNumberOfPages();
            textStripper.setStartPage(1);
            textStripper.setEndPage(Math.min(200, totalPages)); // 限制前200页

            String content = textStripper.getText(document);

            if (content == null || content.trim().isEmpty()) {
                log.warn("未能从PDF文件中提取到文本内容");
                return "";
            }

            return content;
        } catch (IOException e) {
            log.error("解析PDF文件失败", e);
            throw new RuntimeException("解析PDF文件失败: " + e.getMessage(), e);
        }
    }
}
